package com.demo.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisSessionFactory {
    private static SqlSessionFactory sqlSessionFactory = null;
    static{
        // 一加载类 就创建工厂
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    private MyBatisSessionFactory() {
    }
//    //类线程锁 --
//    private static final Class CLASS_LOCK = MyBatisSessionFactory.class;
//
//    public static SqlSessionFactory initSqlSessionFactory() {
//        String resource = "mybatis-config.xml";
//        InputStream inputStream = null;
//        try {
//            inputStream = Resources.getResourceAsStream(resource);
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }
//        synchronized (CLASS_LOCK) {
//            if (sqlSessionFactory == null) {
//                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//            }
//        }
//        return sqlSessionFactory;
//    }

    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }
    public static SqlSession openSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }
}
